package com.xuan.juc.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        test3();
    }

    /*
    * 抛出异常
    * */

    public static void test1(){
        // 队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        System.out.println(blockingQueue.element()); // 队首元素
        // 队列满 Queue full 抛出异常
//        System.out.println(blockingQueue.add("d"));

        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());
    }

    /*
     * 不抛出异常
     * */

    public static void test2(){
        // 队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));

        System.out.println(blockingQueue.peek());  // 队首元素
//        System.out.println(blockingQueue.offer("d"));  // 返回false 不抛出异常

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll()); // 返回null
    }

    /*
    * 阻塞等待
    *
    * */
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
//        blockingQueue.put("d");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
    }

    /*
     * 超时等待
     *
     * */
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
        blockingQueue.offer("a",1, TimeUnit.SECONDS);
        blockingQueue.offer("b",1, TimeUnit.SECONDS);
        blockingQueue.offer("c",1, TimeUnit.SECONDS);
        blockingQueue.offer("d",1, TimeUnit.SECONDS);

        blockingQueue.poll(1, TimeUnit.SECONDS);
        blockingQueue.poll(1, TimeUnit.SECONDS);
        blockingQueue.poll(1, TimeUnit.SECONDS);
        blockingQueue.poll(1, TimeUnit.SECONDS);
    }
}


